package com.cc.data_explore.gui.main;

import atlantafx.base.controls.ModalPane;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cc.data_explore.gui.tab.TabView;
import com.cc.data_explore.gui.tab.TabViewModel;
import com.cc.data_explore.gui.tab.WorkspaceView;
import com.cc.data_explore.gui.tab.WorkspaceViewModel;
import com.cc.data_explore.logic.mybatis.DbHelper;
import com.cc.data_explore.logic.mybatis.mapper.main.BaseDbMapper;
import com.cc.data_explore.logic.mybatis.model.BaseDb;
import de.saxsys.mvvmfx.*;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.VBox;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.dromara.hutool.core.data.id.IdUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.RandomUtil;

import java.time.LocalDateTime;

/**
 * MainViewController
 *
 * @author aa
 * @version 1.0
 * @since 2025/3/27
 */
public class MainView implements FxmlView<MainViewModel> {

    @FXML
    public TabPane mainTab;
    @FXML
    public Button addDs;
    @FXML
    public Button addView;
    @FXML
    public VBox vbox;

    @InjectViewModel
    private MainViewModel mainViewModel;

    @FXML
    public void initialize() {
        mainViewModel.release();
        mainTab.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            DbHelper.getInstance().DB_NAME.set(newValue.getId());
            System.out.println("aaa");
        });
        // 加载 FXML 文件
        ViewTuple<WorkspaceView, WorkspaceViewModel> load = FluentViewLoader.fxmlView(WorkspaceView.class).load();
        Tab tab = new Tab("工作区", load.getView());
        tab.setClosable(false);
        tab.setId("workspace");
        mainTab.getTabs().add(tab);

        MvvmFX.getNotificationCenter().subscribe("WORKSPACE_CREATE_TAB", (k, v) -> subscribeCreateTab((String) v[0]));
        MvvmFX.getNotificationCenter().subscribe("MAIN_VIEW_DEL_TAB", (k, v) -> subscribeDelTab((String) v[0]));
    }

    private void subscribeDelTab(String tabId) {
        mainTab.getTabs().stream().filter(t -> t.getId().equals(tabId)).findFirst().ifPresent(open -> mainTab.getTabs().remove(open));
    }

    public void createDs(ActionEvent actionEvent) {
        createTab(null);
    }

    public void createTabView(ActionEvent actionEvent) {

    }

    public void subscribeCreateTab(String tabId) {
        System.out.println(tabId);
        ObservableList<Tab> tabs = mainTab.getTabs();
        Tab open = tabs.stream().filter(t -> t.getId().equals(tabId)).findFirst().orElse(null);
        if (open != null) {
            mainTab.getSelectionModel().select(open);
        } else {
            createTab(tabId);
        }
    }

    private void createTab(String dbName) {
        SqlSessionFactory sqlSessionFactory = DbHelper.getInstance().getSqlSessionFactory(DbHelper.MAIN_DB_NAME);
        // 加载 FXML 文件
        try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) {
            if (StrUtil.isEmpty(dbName)) {
                dbName = RandomUtil.randomString(10);
            }
            ViewTuple<TabView, TabViewModel> load = FluentViewLoader.fxmlView(TabView.class).load();
            load.getViewModel().initData(dbName);
            String tabName = "标签2";
            Tab tab = new Tab(tabName, load.getView());
            final String finalDbName = dbName;
            tab.setOnClosed(event -> DbHelper.getInstance().remDb(finalDbName));
            tab.setId(dbName);
            mainTab.getTabs().add(tab);
            mainTab.getSelectionModel().select(tab);
            BaseDbMapper mapper = sqlSession.getMapper(BaseDbMapper.class);
            boolean exists = mapper.exists(Wrappers.<BaseDb>lambdaQuery().eq(BaseDb::getDbFile, dbName));
            if (!exists) {
                BaseDb baseDb = new BaseDb();
                baseDb.setDbName(tabName);
                baseDb.setDbFile(dbName);
                baseDb.setCreateTime(LocalDateTime.now());
                baseDb.setId(IdUtil.getSnowflakeNextId());
                mapper.insert(baseDb);
                MvvmFX.getNotificationCenter().publish("REFRESH_WORKSPACE");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
